from flask import jsonify, request
from ..models.repair import Repair
from ..models.user import User
from ..models.house import House
from ..extensions import db
from ..utils.response import pagination, error, success

# 创建报修记录
def create_repair(data):
    try:
        # 验证必填字段
        if not data.get('house_id') or not data.get('user_id') or not data.get('repair_type'):
            return error('户号、用户ID和报修类型为必填字段', 400)
        
        # 验证用户是否存在
        user = User.query.get(data['user_id'])
        if not user:
            return error('报修用户不存在', 400)
        
        # 创建报修实例
        repair = Repair(
            house_id=data['house_id'],
            user_id=data['user_id'],
            repair_type=data['repair_type'],
            appointment_time=data.get('appointment_time'),
            is_solved=data.get('is_solved', False)
        )
        
        db.session.add(repair)
        db.session.commit()
        
        return success('报修记录创建成功', repair.to_dict())
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 获取报修列表
def get_repairs(data):
    """获取报修列表，支持按用户ID、是否解决筛选，支持分页"""
    try:
        user_id = data.get('user_id')
        is_solved = data.get('is_solved')

        # 连表查询（带上房屋名和用户名）
        query = (
            Repair.query
            .join(House, Repair.house_id == House.id)
            .join(User, Repair.user_id == User.id)
            .add_columns(
                Repair.id,
                Repair.house_id,
                Repair.user_id,
                Repair.repair_type,
                Repair.appointment_time,
                Repair.is_solved,
                House.name.label('house_name'),
                User.name.label('user_name')
            )
        )

        # 筛选
        if user_id:
            query = query.filter(Repair.user_id == user_id)
        if is_solved is not None:
            query = query.filter(Repair.is_solved == bool(int(is_solved)))

        # 统计总数
        total = query.count()

        # 排序 + 分页
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        page = max(1, page)
        page_size = min(max(1, page_size), 100)
        offset = (page - 1) * page_size

        rows = query.order_by(Repair.id.desc()).offset(offset).limit(page_size).all()

        repairs = []
        for row in rows:
            repair_obj = row[0]
            house_name = row[-2]
            user_name = row[-1]
            print(row)
            repairs.append({
                **repair_obj.to_dict(),  # 如果 Repair 有 to_dict()
                "house_name": house_name,
                "user_name": user_name
            })

        return pagination(
            items=repairs,
            total=total,
            msg='获取成功',
            code=200
        )

    except Exception as e:
        print(f"Error in get_repairs: {str(e)}")
        return error('获取失败', 500)

# 获取单个报修记录
def get_repair():
    try:
        repair_id = request.args.get('id')
        
        if not repair_id:
            return error('未提供报修ID', 400)
        
        repair = Repair.query.get(repair_id)
        
        if not repair:
            return error('报修记录不存在', 404)
        
        return success('获取成功', repair.to_dict())
    except Exception as e:
        return error(str(e), 500)   

# 更新报修记录
def update_repair():
    try:
        data = request.json
        repair_id = data.get('id')
        
        if not repair_id:
            return error('未提供报修ID', 400)
        
        repair = Repair.query.get(repair_id)
        
        if not repair:
            return error('报修记录不存在', 404)
        
        # 更新字段
        if 'house_id' in data:
            repair.house_id = data['house_id']
        if 'repair_type' in data:
            repair.repair_type = data['repair_type']
        if 'appointment_time' in data:
            repair.appointment_time = data['appointment_time']
        if 'is_solved' in data:
            repair.is_solved = data['is_solved']
        # user_id 不允许修改，保持数据一致性
        
        db.session.commit()
        
        return success('报修记录更新成功', repair.to_dict())
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)

# 删除报修记录
def delete_repair():
    try:
        data = request.json
        repair_id = data.get('id')
        
        if not repair_id:
            return error('未提供报修ID', 400)
        
        repair = Repair.query.get(repair_id)
        
        if not repair:
            return error('报修记录不存在', 404)
        
        db.session.delete(repair)
        db.session.commit()
        
        return success('报修记录删除成功', repair.to_dict())    
    except Exception as e:
        db.session.rollback()
        return error(str(e), 500)
